<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

/* 设置缓存 可自定义时间*/

use app\common\model\AgentModel;
use app\common\model\AnchorLevelRuleModel;
use app\common\model\AnchorFansModel;
use app\common\model\ConfigPriModel;
use app\common\model\ConfigPubModel;
use app\common\model\ConfigTagModel;
use app\common\model\FootballMatchAttentModel;
use app\common\model\GiftLogModel;
use app\common\model\MomentLikeModel;
use app\common\model\MomentCollectModel;
use app\common\model\MomentCommentLikeModel;
use app\common\model\ShortvideoLikeModel;
use app\common\model\ShortvideoCommentLikeModel;
use app\common\model\ShortvideoCollectModel;
use app\common\model\SmscodeModel;
use app\common\model\UserLevelRuleModel;
use app\common\model\VisitorLogModel;
use Qcloud\Sms\SmsSingleSender;
use think\facade\Cache;
use think\facade\Env;

function redis_set($key, $value, $time = 0)
{
    if ($time < 0) {
        $time = null;
    }

    return Cache::store('redis')->set($key, json_encode($value), $time);
}

/**
 * 获取客户端的IP地址
 * @param int $type 0 返回IP地址， 1 返回IPV4地址数字
 * @return mixed
 */
function get_client_ip($type = 0)
{
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL) return $ip[$type];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos = array_search('unknown', $arr);
        if (false !== $pos) unset($arr[$pos]);
        $ip = trim($arr[0]);
    } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = ip2long($ip);
    $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/* 获取缓存 */
function redis_get($key)
{
    return json_decode(Cache::store('redis')->get($key), true) ?? [];
}

/* 删除缓存 */
function redis_del($key)
{
    return Cache::store('redis')->rm($key);
}

function getConfigPri()
{
    $key = 'go_webapi_ConfigPri';
    $configPri_redis = redis_get($key);
    if (!$configPri_redis) {
        $configPri = ConfigPriModel::find(1);
        if (!redis_set($key, $configPri)) {
            redis_del($key);
        }

        return $configPri;
    }

    return new ConfigPriModel($configPri_redis);
}

function getConfigPub()
{
    $key = 'go_webapi_ConfigPub';
    $configPub_redis = redis_get($key);
    if (!$configPub_redis) {
        $configPub = ConfigPubModel::find(1);
        if (!redis_set($key, $configPub)) {
            redis_del($key);
        }

        return $configPub;
    }

    return new ConfigPubModel($configPub_redis);
}

function getConfigTag()
{
    $key = "ConfigTag";
    $configTag_redis = redis_get($key);
    if (!$configTag_redis) {
        $configTag = ConfigTagModel::order('type', 'desc')->all();
        if (!redis_set($key, $configTag)) {
            redis_del($key);
        }
        return $configTag;
    }

    return new ConfigTagModel($configTag_redis);
}

function nowFormat()
{
    return date('Y-m-d H:i:s');
}

function createInviteCode()
{
    $invite_code = '';
    for ($i = 1; $i <= 6; $i++) {
        $invite_code .= chr(mt_rand(65, 90));
    }
    //查询是否已存在
    if ($isexist = AgentModel::where('invite_code', $invite_code)->find()) {
        return createInviteCode();
    }

    return $invite_code;
}

function getAnchorRoomID($anchorid)
{
    return "LIVEROOM_{$anchorid}";
}

function getAnchorIDByGroup($groupid)
{
    if (strlen($groupid) > 9) {
        return substr($groupid, 9);
    }
    return false;
}

/**
 * @desc 腾讯云推拉流地址
 * @param $host string 协议 如:http rtmp
 * @param $stream string 流名 如有则包含 .flv、.m3u8
 * @param $type int 类型 0表示播流1表示推流
 * @return string
 */
function CreateLiveUrl($host, $stream, $type)
{
    $configpri = getConfigPri();
    $push_url_key = $configpri['push_key'];
    $push = $configpri['push_domain'];
    $pull = $configpri['pull_domain'];

    $now_time = time() + 3 * 60 * 60;
    $txTime = dechex($now_time);

    $txSecret = md5($push_url_key . $stream . $txTime);
    $safe_url = "&txSecret=" . $txSecret . "&txTime=" . $txTime;

    if ($type == 1) {
        return "rtmp://{$push}/live/" . $stream . "?" . $safe_url;
    }

    if ($host == 'rtmp') {
        return "rtmp://{$pull}/live/" . $stream . "?" . $safe_url;
    }

    if ($host == 'flv') {
        return "https://{$pull}/live/" . $stream . ".flv";
    }

    if ($host == 'm3u8') {
        return "https://{$pull}/live/" . $stream . ".m3u8";
    }

    return '';
}

/*
 * 请求处理
 * @param $url
 * @param $data
 */
function httpHelper($url, $data, $header = null)
{
    $user_agent = 'Mozilla/4.0+(compatible;+MSIE+6.0;+Windows+NT+5.1;+SV1)';
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);        //返回结果
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    if ($header) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    }
    $r = curl_exec($ch);
    curl_close($ch);
    return $r;
}

/*
 * 请求处理
 * @param $url
 * @param $data
 */
function httpGetHelper($url, $header = null)
{
    $user_agent = 'Mozilla/4.0+(compatible;+MSIE+6.0;+Windows+NT+5.1;+SV1)';
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, false);
    curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);        //返回结果
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    if ($header) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    }
    $r = curl_exec($ch);
    curl_close($ch);
    return $r;
}

// ---------------------------------------------------  业务相关公共方法  --------------------------------------------------------

function sendCode($mobile, $code, $ip)
{
    try {
        $configPriModel = getConfigPri();
        $ssender = new SmsSingleSender($configPriModel->qsms_appid, $configPriModel->qsms_appkey);
        $params = [$code, '30'];
        $result = $ssender->sendWithParam(
            "86",
            $mobile,
            $configPriModel->qsms_tplid,
            $params,
            $configPriModel->qsms_sign,
            "",
            ""
        );
        $rsp = json_decode($result);
        if ($rsp->result == 0) {
            file_put_contents(Env::get('runtime_path') . 'sendCode_' . date('Y-m-d') . '.txt', date('Y-m-d H:i:s') . ' : ' . $mobile . '  :' . json_encode($rsp) . "\r\n", FILE_APPEND);
            $codeModel = new SmscodeModel();
            $codeModel->mobile = $mobile;
            $codeModel->request_ip = $ip;
            $codeModel->create_time = date("Y-m-d H:i:s");
            $codeModel->code = $code;
            $codeModel->save();
            if ($codeModel->id) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    } catch (\Exception $exception) {
        file_put_contents(Env::get('runtime_path') . 'sendCode_' . date('Y-m-d') . '.txt', date('Y-m-d H:i:s') . ' : ' . $mobile . ' :' . json_encode($exception) . "\r\n", FILE_APPEND);
        return false;
    }
}

//计算主播等级
function calculateAnchorLevel($point)
{
    $level = 1;
    $rules = AnchorLevelRuleModel::order('level', 'desc')->select();
    foreach ($rules as $rule) {
        if ($point >= $rule->point && $rule->level > $level) {
            $level = $rule->level;
        }
    }
    return $level;
}

//计算用户等级
function calculateUserLevel($point)
{
    $level = 1;
    $rules = UserLevelRuleModel::order('level', 'desc')->select();
    foreach ($rules as $rule) {
        if ($point >= $rule->point && $rule->level > $level) {
            $level = $rule->level;
        }
    }
    return $level;
}

/*
 * 主播直播加经验
 * @param $duration 直播时长 单位S
 */
function addAnchorPointEventLive($duration)
{
    return $duration / 60 / 6; //一小时涨10点经验
}

//用户每日登陆加经验
function addUserPointEventLogin()
{
    return 100;
}

//用户绑定手机加经验
function addUserPointEventBindMobile()
{
    return 500;
}

//用户赠送礼物加经验
function addUserPointEventSendGift($price)
{
    return $price * 10;
}

//用户发布动态加经验
function addUserPointEventPublishMoment()
{
    return 100;
}

//用户解锁动态加经验
function addUserPointEventUnlockMoment($price)
{
    return $price * 10;
}

//用户发布动态加经验
function addUserPointEventPublishShortVideo()
{
    return 100;
}

function index_mb_str($str, $start, $end, $encoding)
{
    if (mb_strlen($str) > $end) {
        $string = mb_substr($str, $start, $end, $encoding) . '....';
    } else {
        $string = mb_substr($str, $start, $end, $encoding);
    }
    return $string;
}


// ---------------------------------------------------  Redis相关公共方法  --------------------------------------------------------

function getAttentCount($uid)
{
    if (!$attentCount = redis_get($key = 'AttentCount_' . $uid)) {
        redis_set($key, $attentCount = AnchorFansModel::where('fansid', $uid)->count());
    }

    return $attentCount;
}

function setAttentCount($uid, $count)
{
    if (!redis_set($key = 'AttentCount_' . $uid, $count)) {
        redis_del($key);
    }
}

function getFansCount($uid)
{
    if (!$fansCount = redis_get($key = 'FansCount_' . $uid)) {
        redis_set($key, $fansCount = AnchorFansModel::where('anchorid', $uid)->count());
    }

    return $fansCount;
}

function setFansCount($uid, $count)
{
    if (!redis_set($key = 'FansCount_' . $uid, $count)) {
        redis_del($key);
    }
}

function getVisitorCount($uid)
{
    $key = 'VisitorCount_' . $uid;
    $visitorCount = redis_get($key);
    if (!$visitorCount) {
        $visitorCount = VisitorLogModel::where('uid', $uid)->count();
        redis_set($key, $visitorCount);
    }
    return $visitorCount;
}

function setVisitorCount($uid, $count)
{
    if (!redis_set($key = 'VisitorCount_' . $uid, $count)) {
        redis_del($key);
    }
}

function getSendGiftCount($uid)
{
    if (!$count = redis_get($key = 'SendGiftCount_' . $uid)) {
        redis_set($key, $count = GiftLogModel::where('uid', $uid)->sum("spend"));
    }

    return $count;
}

function setSendGiftCount($uid, $count)
{
    $key = 'SendGiftCount_' . $uid;
    if (!redis_set($key, $count)) {
        redis_del($key);
    }
}

function getUserLikeMomentIds($uid)
{
    if (!$ids = redis_get($key = 'MomentLikeIds_' . $uid)) {
        $moments = MomentLikeModel::where('uid', $uid)->field('momentid')->select()->toArray();
        redis_set($key, $ids = array_column($moments, 'momentid'));
    }

    return $ids;
}

function setUserLikeMomentIds($uid, $ids = [])
{
    $key = 'MomentLikeIds_' . $uid;
    if (count($ids) == 0) {
        $moments = MomentLikeModel::where('uid', $uid)->field('momentid')->select()->toArray();
        $ids = array_column($moments, 'momentid');
    }
    if (!redis_set($key, $ids)) {
        redis_del($key);
    }
}

function getUserCollectMomentIds($uid)
{
    $key = 'MomentCollectIds_' . $uid;
    $ids = redis_get($key);
    if (!$ids) {
        $moments = MomentCollectModel::where('uid', $uid)->field('momentid')->select()->toArray();
        $ids = array_column($moments, 'momentid');
        redis_set($key, $ids);
    }
    return $ids;
}

function setUserCollectMomentIds($uid, $ids = [])
{
    $key = 'MomentCollectIds_' . $uid;
    if (count($ids) == 0) {
        $moments = MomentCollectModel::where('uid', $uid)->field('momentid')->select()->toArray();
        $ids = array_column($moments, 'momentid');
    }
    if (!redis_set($key, $ids)) {
        redis_del($key);
    }
}

function getUserLikeMomentCommentIds($uid)
{
    $key = 'MomentCommentLikeIds_' . $uid;
    $ids = redis_get($key);
    if (!$ids) {
        $comments = MomentCommentLikeModel::where('uid', $uid)->field('commentid')->select()->toArray();
        $ids = array_column($comments, 'commentid');
        redis_set($key, $ids);
    }
    return $ids;
}

function setUserLikeMomentCommentIds($uid, $ids = [])
{
    $key = 'MomentCommentLikeIds_' . $uid;
    if (count($ids) == 0) {
        $comments = MomentCommentLikeModel::where('uid', $uid)->field('commentid')->select()->toArray();
        $ids = array_column($comments, 'commentid');
    }
    if (!redis_set($key, $ids)) {
        redis_del($key);
    }
}

function getUserLikeShortVideoIds($uid)
{
    $key = 'ShortVideoLikeIds_' . $uid;
    $ids = redis_get($key);
    if (!$ids) {
        $videos = ShortvideoLikeModel::where('uid', $uid)->field('videoid')->select()->toArray();
        $ids = array_column($videos, 'videoid');
        redis_set($key, $ids);
    }
    return $ids;
}

function setUserLikeShortVideoIds($uid, $ids = [])
{
    $key = 'ShortVideoLikeIds_' . $uid;
    if (count($ids) == 0) {
        $videos = ShortvideoLikeModel::where('uid', $uid)->field('videoid')->select()->toArray();
        $ids = array_column($videos, 'videoid');
    }
    if (!redis_set($key, $ids)) {
        redis_del($key);
    }
}

function getUserLikeShortVideoCommentIds($uid)
{
    $key = 'ShortVideoCommentLikeIds_' . $uid;
    $ids = redis_get($key);
    if (!$ids) {
        $comments = ShortvideoCommentLikeModel::where('uid', $uid)->field('commentid')->select()->toArray();
        $ids = array_column($comments, 'commentid');
        redis_set($key, $ids);
    }
    return $ids;
}

function setUserLikeShortVideoCommentIds($uid, $ids = [])
{
    $key = 'ShortVideoCommentLikeIds_' . $uid;
    if (count($ids) == 0) {
        $comments = ShortvideoCommentLikeModel::where('uid', $uid)->field('commentid')->select()->toArray();
        $ids = array_column($comments, 'commentid');
    }
    if (!redis_set($key, $ids)) {
        redis_del($key);
    }
}

function getUserCollectShortVideoIds($uid)
{
    $key = 'ShortVideoCollectIds_' . $uid;
    $ids = redis_get($key);
    if (!$ids) {
        $videos = ShortvideoCollectModel::where('uid', $uid)->field('videoid')->select()->toArray();
        $ids = array_column($videos, 'videoid');
        redis_set($key, $ids);
    }
    return $ids;
}

function setUserCollectShortVideoIds($uid, $ids = [])
{
    $key = 'ShortVideoCollectIds_' . $uid;
    if (count($ids) == 0) {
        $videos = ShortvideoCollectModel::where('uid', $uid)->field('videoid')->select()->toArray();
        $ids = array_column($videos, 'videoid');
    }
    if (!redis_set($key, $ids)) {
        redis_del($key);
    }
}

function getUserAttentAnchorIds($uid)
{
    $key = 'AttentAnchorIds_' . $uid;
    $ids = redis_get($key);
    if (!$ids) {
        $anchors = AnchorFansModel::where('fansid', $uid)->field('anchorid')->select()->toArray();
        $ids = array_column($anchors, 'anchorid');
        redis_set($key, $ids);
    }
    return $ids;
}

function setUserAttentAnchorIds($uid, $ids = [])
{
    $key = 'AttentAnchorIds_' . $uid;
    if (count($ids) == 0) {
        $anchors = AnchorFansModel::where('fansid', $uid)->field('anchorid')->select()->toArray();
        $ids = array_column($anchors, 'anchorid');
    }
    if (!redis_set($key, $ids)) {
        redis_del($key);
    }
}

function getUserAttentMatchIds($uid)
{
    $key = 'AttentMatchIds_' . $uid;
    $ids = redis_get($key);
    if (!$ids) {
        $matchs = FootballMatchAttentModel::where('uid', $uid)->field('matchid')->select()->toArray();
        $ids = array_column($matchs, 'matchid');
        redis_set($key, $ids);
    }
    return $ids;
}

function setUserAttentMatchIds($uid, $ids = [])
{
    $key = 'AttentMatchIds_' . $uid;
    if (count($ids) == 0) {
        $matchs = FootballMatchAttentModel::where('uid', $uid)->field('matchid')->select()->toArray();
        $ids = array_column($matchs, 'matchid');
    }
    if (!redis_set($key, $ids)) {
        redis_del($key);
    }
}

function setLiveAudience($anchorid, $audienceids = [])
{
    $key = 'LiveAudience_' . $anchorid;
    if (count($audienceids) == 0) {
        redis_del($key);
    } elseif (!redis_set($key, $audienceids)) {
        redis_del($key);
    }
}

function getLiveAudience($anchorid)
{
    if (!$audienceids = redis_get('LiveAudience_' . $anchorid)) {
        return [];
    }

    return $audienceids;
}

function diffTime($start_time, $end_time): string
{
    $hour = floor((($end_time) - ($start_time)) % 86400 / 3600);
    $minute = floor((($end_time) - ($start_time)) % 86400 / 60);
    $second = floor((($end_time) - ($start_time)) % 86400 % 60);
    $date = floor((($end_time) - ($start_time)) / 86400);
    $str = "";
    if ($date > 0) {
        $str .= $date . "天";
    }
    if ($hour > 0) {
        $str .= $hour . "小时";
    }
    if ($minute > 0) {
        $str .= $hour . "分钟";
    }
    if ($second > 0) {
        $str .= $second . "秒";
    }
    return $str ? $str : " - ";
}


/**
 * 输出到浏览器(需要设置header头)
 * @param string $fileName 文件名
 * @param string $fileType 文件类型
 */
function excelBrowserExport($fileName, $fileType)
{
    //文件名称校验
    if (!$fileName) {
        trigger_error('文件名不能为空', E_USER_ERROR);
    }

    //Excel文件类型校验
    $type = ['Excel2007', 'Xlsx', 'Excel5', 'xls'];
    if (!in_array($fileType, $type)) {
        trigger_error('未知文件类型', E_USER_ERROR);
    }

    if ($fileType == 'Excel2007' || $fileType == 'Xlsx') {
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $fileName . '.xlsx"');
        header('Cache-Control: max-age=0');
    } else { //Excel5
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $fileName . '.xls"');
        header('Cache-Control: max-age=0');
    }
}

function export_excel($data, $title, $fileName, $sheetName = "", $fileType = "Xlsx")
{
    $spreadsheet = new PhpOffice\PhpSpreadsheet\Spreadsheet();
    $worksheet = $spreadsheet->getActiveSheet();

    //设置工作表标题名称
    $worksheet->setTitle($sheetName);

    //表头
    //设置单元格内容
    foreach ($title as $key => $value) {
        $worksheet->setCellValueByColumnAndRow($key + 1, 1, $value);
    }

    $row = 2; //从第二行开始
    foreach ($data as $item) {
        $column = 1;
        foreach ($item as $value) {
            $worksheet->setCellValueByColumnAndRow($column, $row, $value);
            $column++;
        }
        $row++;
    }

    //2.输出到浏览器
    $writer = PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, $fileType); //按照指定格式生成Excel文件
    excelBrowserExport($fileName, $fileType);
    $writer->save('php://output');
}

/**
 * 加密函数
 * @param $str
 * @param string $iv
 * @return false|string
 */
function opensslEnCode($str, $iv = '8bAWJeh0BxXWLByO')
{
    return openssl_encrypt($str, 'aes-256-cbc', config('other.openssl_pass_key'), 0, $iv);
}

/**
 * 解密函数
 * @param $str
 * @param string $iv
 * @return false|string
 */
function opensslDeCode($str, $iv = '8bAWJeh0BxXWLByO')
{
    return openssl_decrypt($str, 'aes-256-cbc', config('other.openssl_pass_key'), 0, $iv);
}

/**
 * 分页导航
 * @param int $pageindex
 * @param int $pagecount
 * @param int $cnt
 * @return array
 */
function page_nav(int $pageindex, int $pagecount, int $cnt = 8): array
{
    $nav[] = $pageindex;
    for ($left = $pageindex - 1, $right = $pageindex + 1; ($left >= 1 || $right <= $pagecount) && count($nav) < $cnt;) {
        if ($left >= 1) {
            array_unshift($nav, $left);
            $left--;
        }
        if ($right <= $pagecount) {
            array_push($nav, $right);
            $right++;
        }
    }
    return $nav;
}

/**
 * 生成订单号
 * @param string $prefix 前缀标示
 * @return string
 */
function createOrderNo($prefix = 'RG')
{
    $microtime = explode(' ', microtime());
    $microtime = $microtime[1] . substr($microtime[0], 2, 6);

    $order_no = date('YmdHis') . substr($microtime, -5) . mt_rand(1000, 9999);
    return $prefix . $order_no;
}


/**
 * 写文件日志
 * @param $contnt
 * @param $file_name
 */
function writeLog($content, $file_name = 'log.txt')
{
    $path_file = app()->getRuntimePath() . "log/{$file_name}";
    $content     = is_array($content) ? json_encode($content, JSON_UNESCAPED_UNICODE) : $content;
    if (!empty($_POST)) {
        $content .= "\r\npost：" . json_encode($_POST, JSON_UNESCAPED_UNICODE);
    }
    return file_put_contents($path_file, date('Y-m-d H:i:s') . PHP_EOL . $content . PHP_EOL . PHP_EOL, FILE_APPEND);
}

/**
 * 隐藏手机号中间位数
 * @param $mobile
 */
function mobileHide($mobile, $role_id = 0)
{
    if ($role_id == 11) {
        return $mobile;
    }
    if (preg_match(config('other.mobile_preg'), $mobile)) {
        return  substr_replace($mobile, "****", 3, 6);
    }
    return $mobile;
}

/**
 * 获取毫秒时间戳
 */
function getMicrotime()
{
    $microtime = explode(' ', microtime());
    return ($microtime[1] . substr($microtime[0], 2, 3));
}


/**
 * 获取某周的开始时间 结束时间
 * @param $year
 * @param $weeknum
 * @return array
 */
function getWeekDate($year, $weeknum)
{
    $firstdayofyear = mktime(0, 0, 0, 1, 1, $year);
    $firstweekday = date('N', $firstdayofyear);
    $firstweenum = date('W', $firstdayofyear);
    if ($firstweenum == 1) {
        $day = (1 - ($firstweekday - 1)) + 7 * ($weeknum - 1);
        $startdate = date('Y-m-d', mktime(0, 0, 0, 1, $day, $year));
        $enddate = date('Y-m-d', mktime(0, 0, 0, 1, $day + 6, $year));
    } else {
        $day = (9 - $firstweekday) + 7 * ($weeknum - 1);
        $startdate = date('Y-m-d', mktime(0, 0, 0, 1, $day, $year));
        $enddate = date('Y-m-d', mktime(0, 0, 0, 1, $day + 6, $year));
    }

    return [$startdate . ' 00:00:00', $enddate . ' 23:59:59'];
}


// get lang field
function Lang($key)
{
    $lang = config('other.default_language');
    $lang_pack = include("../application/lang/{$lang}.php");
    return $lang_pack[$key];
}
